package com.fernfx.xingtan.main.ui;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.base.BaseActivity;
import com.fernfx.xingtan.contacts.ui.AddFriendsActivity;
import com.fernfx.xingtan.main.adapter.SelectLocationAdapter;
import com.fernfx.xingtan.main.contract.SelectLocationContract;
import com.fernfx.xingtan.main.entity.SelectLocationResultEntity;
import com.fernfx.xingtan.main.presenter.SelectLocationPresenter;
import com.fernfx.xingtan.utils.CollectionUtil;
import com.fernfx.xingtan.utils.FragmentFactoryUtil;
import com.fernfx.xingtan.utils.OtherUtil;
import com.fernfx.xingtan.utils.SoftInputUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * Created by admin on 2018/8/22.
 * 选择坐标
 */

public class SelectLocationActivity extends BaseActivity implements View.OnClickListener, SelectLocationContract.View, AdapterView.OnItemClickListener{
    public static final int SELECT_LOCATION_STATUS = 1;

    public static void start(BaseActivity context) {
        Intent intent = new Intent(context, SelectLocationActivity.class);
        context.startActivityForResult(intent,SELECT_LOCATION_STATUS);
    }

    @BindView(R.id.baidu_map_tvw)
    TextureMapView baiduMapTvw;
    @BindView(R.id.recommend_area_liv)
    ListView recommendAreaLiv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.select_location_rlt)
    ViewGroup selectLocationRlt;
    @BindView(R.id.search_line_vw)
    View searchLineVw;
    @BindView(R.id.search_area_liv)
    ListView searchAreaLiv;
    @BindView(R.id.finish_current_tv)
    TextView finishCurrentTv;

    private SelectLocationContract.Presenter presenter;
    private ArrayList<PoiInfo> mInfoList = new ArrayList<>(0);
    //百度地图
    BaiduMap mBaiduMap;
    private SelectLocationAdapter selectLocationAdapter;
    //true 执行 false不执行
    private boolean runningFlag = false;

    //search
    private ArrayList<PoiInfo> searchInfoList = new ArrayList<>(0);
    private SelectLocationAdapter searchLocationAdapter;
    //经纬度
    private String latitudeText,longitudeText,selectText;
    //状态默认为一公里
    private int range = 3;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_robred_packet_location;
    }

    @Override
    protected int getAppBarLayoutResId() {
        return -1;
    }

    @Override
    protected void initView() {
        presenter = new SelectLocationPresenter();
        presenter.init(this);
        mBaiduMap = presenter.initBaiduMap(baiduMapTvw);
        //set adapter
        selectLocationAdapter = new SelectLocationAdapter(mContext, mInfoList);
        recommendAreaLiv.setAdapter(selectLocationAdapter);
        //search
        searchLocationAdapter = new SelectLocationAdapter(mContext, searchInfoList);
        searchAreaLiv.setAdapter(searchLocationAdapter);
    }

    @Override
    protected void initListener() {
        //register listener
        recommendAreaLiv.setOnItemClickListener(this);
        searchAreaLiv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //关闭搜索页面
                changeListener.onClick(view);
                //切换定位
                PoiInfo info = (PoiInfo) searchLocationAdapter.getItem(position);
                LatLng la = info.location;
                String name = info.name;

                MyLocationData data = new MyLocationData.Builder()
                        .latitude(la.latitude)
                        .longitude(la.longitude)
                        .build();
                //赋值经纬度
                latitudeText = String.valueOf(la.latitude);
                longitudeText = String.valueOf(la.longitude);

                mBaiduMap.setMyLocationData(data);
                // 动画跳转
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(la);
                mBaiduMap.animateMapStatus(u);
                presenter.getMLoactionLatLng().stop();
            }
        });

        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputText = s.toString();
                if (TextUtils.isEmpty(inputText)) {
                    return;
                }
                if (!runningFlag) {
                    visibleButton(View.GONE);
                    runningFlag = true;
                    //重新设置点击事件
                    finishCurrentTv.setOnClickListener(null);
                    finishCurrentTv.setOnClickListener(changeListener);
                }
                presenter.getPoiSearch().searchInCity((new PoiCitySearchOption())
                        .city(presenter.getCity())
                        .keyword(inputText)
                        .pageNum(1));

            }
        });
    }

    private View.OnClickListener changeListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            //关闭键盘
            SoftInputUtil.hideSoftInput(mContext,searchEdit);
            searchEdit.setText("");
            runningFlag = false;
            visibleButton(View.VISIBLE);
            //重新注册点击事件
            finishCurrentTv.setOnClickListener(null);
            finishCurrentTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        mBaiduMap.setMyLocationEnabled(true);
        if (!presenter.getMLoactionLatLng().isStarted()) {
            //开启定位
            presenter.getMLoactionLatLng().start();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        baiduMapTvw.onResume();
    }

    @OnClick({R.id.finish_current_tv, R.id.select_location_clt,R.id.confim_tv})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_location_clt:
                SoftInputUtil.hideKeyboard(this);
                break;
            case R.id.finish_current_tv:
                finish();
                break;
            case R.id.confim_tv:
                //如果用户没有选择过
                if (TextUtils.isEmpty(latitudeText)) {
                    latitudeText = String.valueOf(presenter.getCurrentLatLng().latitude);
                }
                if (TextUtils.isEmpty(longitudeText)){
                    longitudeText = String.valueOf(presenter.getCurrentLatLng().longitude);
                }
                //init entity
                SelectLocationResultEntity sLocationResultEntity = new SelectLocationResultEntity();
                sLocationResultEntity.setLatitudeText(latitudeText);
                sLocationResultEntity.setLongitudeText(longitudeText);
                sLocationResultEntity.setRange(range);
                sLocationResultEntity.setSelectText(selectText);
                EventBus.getDefault().post(sLocationResultEntity);
                finish();
                break;
        }
    }

    @OnCheckedChanged({R.id.one_km_rbn, R.id.area_km_rbn,R.id.city_km_rbn})
    public void onRadioButtonCheckChanged(CompoundButton button, boolean checked) {
        if (!checked) {
            return;
        }
        switch (button.getId()) {
            case R.id.one_km_rbn:
                //获取经纬度
                latitudeText = String.valueOf(presenter.getCurrentLatLng().latitude);
                longitudeText = String.valueOf(presenter.getCurrentLatLng().longitude);
                //一公里
                range = 3;
                selectText = "附近一公里";

                mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(19));
                break;
            case R.id.area_km_rbn:
                //区县
                range = 2;
                latitudeText = presenter.getCity();
                longitudeText = presenter.getDistrict();

                selectText = "全区/县";

                mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(13));
                break;
            case R.id.city_km_rbn:
                //城市
                range = 1;
                latitudeText = presenter.getCity();
                longitudeText = "";

                selectText = "全市";

                mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(11));
                break;
        }
    }

    @Override
    public BaseActivity getActivity() {
        return this;
    }

    @Override
    public void showRecommendLocation(List<PoiInfo> mInfoList) {
        this.mInfoList.clear();
        this.mInfoList.addAll(mInfoList);
        //set adapter data
        if (selectLocationAdapter != null) {
            selectLocationAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void searchLocation(List<PoiInfo> mInfoList) {
        searchInfoList.clear();
        searchInfoList.addAll(mInfoList);
        if (searchLocationAdapter != null) {
            searchLocationAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PoiInfo info = (PoiInfo) selectLocationAdapter.getItem(position);
        LatLng la = info.location;
        String name = info.name;

        MyLocationData data = new MyLocationData.Builder()
                .latitude(la.latitude)
                .longitude(la.longitude)
                .build();
        //赋值经纬度
        latitudeText = String.valueOf(la.latitude);
        longitudeText = String.valueOf(la.longitude);

        mBaiduMap.setMyLocationData(data);
        // 动画跳转
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(la);
        mBaiduMap.animateMapStatus(u);
        presenter.getMLoactionLatLng().stop();
    }

    private void visibleButton(int visible){
        if (View.GONE == visible) {
            baiduMapTvw.setVisibility(visible);
            recommendAreaLiv.setVisibility(visible);
            selectLocationRlt.setVisibility(visible);
            searchLineVw.setVisibility(visible);
            searchAreaLiv.setVisibility(View.VISIBLE);
        }else {
            baiduMapTvw.setVisibility(visible);
            recommendAreaLiv.setVisibility(visible);
            selectLocationRlt.setVisibility(visible);
            searchLineVw.setVisibility(visible);
            searchAreaLiv.setVisibility(View.GONE);
        }
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // 停止定位功能
        mBaiduMap.setMyLocationEnabled(false);
        //停止定位
        presenter.getMLoactionLatLng().stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != baiduMapTvw) {
            baiduMapTvw.onDestroy();
            baiduMapTvw = null;
        }
        if (presenter != null) {
            presenter.detachView();
            presenter = null;
        }
        if (!CollectionUtil.isEmpty(mInfoList)) {
            mInfoList.clear();
            mInfoList = null;
        }
        if (null != selectLocationAdapter) {
            selectLocationAdapter = null;
        }
        if (null != changeListener) {
            changeListener = null;
        }
        if (!CollectionUtil.isEmpty(searchInfoList)) {
            searchInfoList.clear();
            searchInfoList = null;
        }
        if (searchLocationAdapter != null) {
            searchLocationAdapter = null;
        }
    }
}
